<template>
	<div style="width: 200px;">
		<el-select :value="curDepartment" filterable  placeholder="无" size="mini" @change="choosedep">
			<el-option-group v-for="group in departmentList" :key="group.label" :label="group.label">
				<el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
					<span style="float: left; font-size: 12px">{{ item.label }}</span>
					<span
						style="float: right; color: #8492a6; font-size: 10px;margin-left: 3px;">{{ item.right_label }}</span>
				</el-option>
			</el-option-group>
		</el-select>
	</div>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		getToken,
		getDoorToken
	} from '@/utils/auth'
	export default {
		name: 'DepartmentSelect',
		data() {
			return {}
		},
		computed: {
			...mapGetters([
				'curDepartment',
				'departmentList'
			])
		},
		methods: {
			getCurDep() {
				let cur = this.$store.getters.curDepartment
				let company = '0'
				if (('' + cur).indexOf('_') != -1) {
					company = ('' + cur).split('_')[0]
				} else {
					company = ('' + cur)
				}
				return company
			},
			choosedep(e) {
				const that = this
				let company_id = '0'
				if (('' + e).indexOf('_') != -1) {
					company_id = ('' + e).split('_')[0]
				} else {
					company_id = ('' + e)
				}

				let cur = that.getCurDep()
				const pageLoading = that.$loading({
					lock: true,
					text: '跳转中',
					spinner: 'el-icon-loading'
				});

				if (cur !== company_id) {
					if (that.getCurDep() === '0') {
						that.$store
							.dispatch('user/doorChooseOrg', {
								company_id
							}).then(async res => {
								pageLoading.close()
								that.chooseSuccess(res, e, company_id)
							})
							.catch(() => {
								pageLoading.close()
							})
					}
					if (that.getCurDep() !== '0') {
						that.$store
							.dispatch('user/chooseOrg', {
								company_id
							}).then(async res => {
								pageLoading.close()
								that.chooseSuccess(res, e, company_id)
							})
							.catch(() => {
								pageLoading.close()
							})
					}
				} else {
					that.$store.commit('company/SET_DEPARTMENT', '' + e);
					pageLoading.close()
				}
			},
			async chooseSuccess(res, e, company_id) {
				const that = this
				await that.$store.dispatch('user/removeRights');
				that.$store.commit('company/SET_DEPARTMENT', '' + e);
				if ('' + company_id === '0') {
					await that.$store.dispatch('user/resetToken');
					that.$router.push({
						path: "/door_index"
					});
				} else {
					await that.$store.dispatch('user/resetDoorToken');
					that.$router.push({
						path: "/index"
					});
				}
			}
		}
	}
</script>

<style>
</style>
